import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from 'src/entities/message.entity';
import { Post } from 'src/entities/post.entity';
import { User } from 'src/entities/user.entity';
import { CreateMessageDTO } from 'src/dto/message/create-message.dto';

@Injectable()
export class MessageService {
  constructor(
    @InjectRepository(Message) private messageRepository: Repository<Message>,
    @InjectRepository(Post) private postRepository: Repository<Post>,
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {}

  /**
   * 创建评论
   * @param postId 文章ID
   * @param userId 用户ID
   * @param createMessageDTO 评论数据
   * @returns 创建的评论
   */
  async createMessage(
    postId: number,
    userId: number,
    createMessageDTO: CreateMessageDTO,
  ): Promise<Message> {
    // 检查文章是否存在
    const post = await this.postRepository.findOneBy({ id: postId });
    if (!post) {
      throw new NotFoundException('文章不存在');
    }

    // 检查用户是否存在
    const user = await this.userRepository.findOneBy({ id: userId });
    if (!user) {
      throw new NotFoundException('用户不存在');
    }

    // 创建评论
    const message = this.messageRepository.create({
      ...createMessageDTO,
      post,
      user,
      createdAt: new Date(),
    });

    return this.messageRepository.save(message);
  }

  /**
   * 获取文章的所有评论
   * @param postId 文章ID
   * @returns 评论列表
   */
  async getMessagesByPostId(postId: number): Promise<Message[]> {
    // 检查文章是否存在
    const post = await this.postRepository.findOneBy({ id: postId });
    if (!post) {
      throw new NotFoundException('文章不存在');
    }

    return this.messageRepository.find({
      where: { post: { id: postId } },
      order: { createdAt: 'ASC' }, // 按创建时间升序排列
    });
  }

  /**
   * 删除评论
   * @param messageId 评论ID
   * @param userId 用户ID
   * @returns 删除结果
   */
  async deleteMessage(messageId: number, userId: number): Promise<{
    success: boolean;
    message: string;
  }> {
    // 检查评论是否存在
    const message = await this.messageRepository.findOne({
      where: { id: messageId },
      relations: ['user'],
    });

    if (!message) {
      return {
        success: false,
        message: '评论不存在',
      };
    }

    // 验证是否是评论作者
    if (message.user.id !== userId) {
      return {
        success: false,
        message: '您无权删除此评论',
      };
    }

    await this.messageRepository.delete(messageId);

    return {
      success: true,
      message: '评论删除成功',
    };
  }
}